package com.fenfen.novel.utils;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;

import com.fenfen.novel.db.NovelDBProvider;
import com.fenfen.novel.db.NovelDownStatus;
import com.fenfen.novel.db.NovelReadRecord;
import com.fenfen.novel.fragment.NovelReadLogFragment;

import java.util.Date;
import java.util.List;

public class NovelRecordHandlerThread extends HandlerThread {

  private static final String TAG = "novel_record_handler";

  private final static int MESSAGE_QUERY_LIST = 1;
  private final static int MESSAGE_QUERY_ONE = 2;
  private final static int MESSAGE_UPDATE_NOVEL = 3;  //更新novel_record中novel部分内容
  private final static int MESSAGE_UPDATE_CHAPTER = 4; //更新novel_record中chapter部分内容
  private final static int MESSAGE_UPDATE_ALL = 5; //更新novel_record中所有内容
  private final static int MESSAGE_SAVE = 6;    //新增novel_record记录
  private final static int MESSAGE_UPDATE_NOTIFY = 7; //novel_record有更新通知
  private static final int MESSAGE_CREATE_DOWN_STATUS = 8; //新增novel_down_status记录
  private static final int MESSAGE_QUERY_DOWN_STATUS = 9; //查询指定novel id的下载状态
  private Context mContext;
  private Handler mainHandler;
  private HandlerListener mListener;

  public abstract static class HandlerListener {
    public void onQueryList(List<NovelReadRecord> list) {
    }

    public void onQueryOne(NovelReadRecord record) {

    }

    public void onQueryOne(NovelReadRecord record, int chapterOrder, int chapterId) {
    }

    public void onQueryDownStatus(String status) {

    }
  }

  public void setHandlerListener(HandlerListener listener) {
    this.mListener = listener;
  }

  public NovelRecordHandlerThread(Context context, Handler handler) {
    super(TAG);
    this.mContext = context;
    this.mainHandler = handler;
  }

  private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      NovelDBProvider db = NovelDBProvider.getInstance(mContext);
      switch (msg.what) {
        case MESSAGE_QUERY_LIST:
          int page = msg.arg1;
          final List<NovelReadRecord> list = db.getReadRecordsByPage(page);
          mainHandler.post(new Runnable() {
            @Override
            public void run() {
              if (mListener != null) {
                mListener.onQueryList(list);
              }
            }
          });
          break;
        case MESSAGE_QUERY_ONE:
          int novelId = msg.arg1;
          final String obj = (String) msg.obj;
          final NovelReadRecord record = db.getReadRecordByNovelId(novelId);
          mainHandler.post(new Runnable() {
            @Override
            public void run() {
              if (mListener != null) {
                if (obj != null) {
                  String[] info = obj.split(",");
                  mListener.onQueryOne(record, Integer.parseInt(info[0]), Integer.parseInt(info[1]));
                } else {
                  mListener.onQueryOne(record);
                }
              }
            }
          });
          break;
        case MESSAGE_QUERY_DOWN_STATUS:
          final NovelDownStatus status = db.getNovelDownStatusById(msg.arg1);
          mainHandler.post(new Runnable() {
            @Override
            public void run() {
              if (mListener != null) {
                String downStatus = CommonUtil.DOWN_STATUS.DEFAULT;
                if(status != null) {
                  downStatus = status.getDownStatus();
                }
                mListener.onQueryDownStatus(downStatus);
              }
            }
          });
          break;
        case MESSAGE_SAVE:
          NovelReadRecord recordSave = (NovelReadRecord) msg.obj;
          db.saveReadRecord(recordSave);
          break;
        case MESSAGE_UPDATE_NOVEL:
          NovelReadRecord recordNovelUpd = (NovelReadRecord) msg.obj;
          db.updateReadRecordNovel(recordNovelUpd);
          break;
        case MESSAGE_UPDATE_CHAPTER:
          NovelReadRecord recordChapterUpd = (NovelReadRecord) msg.obj;
          db.updateReadRecordChapter(recordChapterUpd);
          break;
        case MESSAGE_UPDATE_ALL:
          NovelReadRecord recordAllUpd = (NovelReadRecord) msg.obj;
          db.updateReadRecordAll(recordAllUpd);
          break;
        case MESSAGE_UPDATE_NOTIFY:
          NovelReadLogFragment.setDataStatus(CommonUtil.DB_DATA_STATUS.UPDATE);
          break;
        case MESSAGE_CREATE_DOWN_STATUS:
          NovelReadRecord recordSave2 = (NovelReadRecord) msg.obj;
          NovelDownStatus novelDownStatus = new NovelDownStatus();
          novelDownStatus.setNovelId(recordSave2.getNovelId());
          novelDownStatus.setCreate_time(recordSave2.getCreate_time());
          novelDownStatus.setCreate_time(recordSave2.getUpdate_time());
          novelDownStatus.setDownStatus(CommonUtil.DOWN_STATUS.DOWNING);
          boolean result = db.saveDownStatus(novelDownStatus, recordSave2);
          if(result) {
            Message.obtain(mHandler, MESSAGE_UPDATE_NOTIFY).sendToTarget();
          }
          break;
        default:
          break;
      }
      if (msg.what == MESSAGE_UPDATE_ALL || msg.what == MESSAGE_UPDATE_CHAPTER || msg.what == MESSAGE_UPDATE_NOVEL || msg.what == MESSAGE_SAVE) {
        Message.obtain(mHandler, MESSAGE_UPDATE_NOTIFY).sendToTarget();
      }
      super.handleMessage(msg);
    }
  };

  public void queryByPage(int page) {
    Message msg = Message.obtain();
    msg.what = MESSAGE_QUERY_LIST;
    msg.arg1 = page;
    mHandler.sendMessage(msg);
  }

  public void queryByNovelId(int novelId) {
    Message msg = Message.obtain();
    msg.what = MESSAGE_QUERY_ONE;
    msg.arg1 = novelId;
    mHandler.sendMessage(msg);
  }

  public void queryDownInfoByNovelId(int novelId) {
    Message msg = Message.obtain();
    msg.what =  MESSAGE_QUERY_DOWN_STATUS;
    msg.arg1 = novelId;
    mHandler.sendMessage(msg);
  }

  public void queryByNovelIdAndChapter(int novelId, int chapterOrder, int chapterId) {
    Message msg = Message.obtain();
    msg.what = MESSAGE_QUERY_ONE;
    msg.arg1 = novelId;
    msg.obj = TextUtils.join(",", new Object[]{chapterOrder, chapterId});
    mHandler.sendMessage(msg);
  }

  public void save(NovelReadRecord record) {
    Message.obtain(mHandler, MESSAGE_SAVE, record).sendToTarget();
  }

  public void updateRecordWithNovel(NovelReadRecord record) {
    Message.obtain(mHandler, MESSAGE_UPDATE_NOVEL, record).sendToTarget();
  }

  public void updateRecordWithChapter(NovelReadRecord record) {
    Message.obtain(mHandler, MESSAGE_UPDATE_CHAPTER, record).sendToTarget();
  }

  public void updateRecordWithAll(NovelReadRecord record) {
    Message.obtain(mHandler, MESSAGE_UPDATE_ALL, record).sendToTarget();
  }

  public void saveDownStatus(NovelReadRecord record) {
    Message.obtain(mHandler, MESSAGE_CREATE_DOWN_STATUS, record).sendToTarget();
  }

}
